#include "mainwindow.h"
#include "storage.h"
#include <QListWidget>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent), curIndex(-1)
{
    ui.setupUi(this);

    data = Storage::load("data.db");

    for(int i = 0; i < data.size(); ++i)
    {
        ui.listWidget->addItem(data[i].name + " " + data[i].surname);
    }
}

void MainWindow::showData(int row)
{    
    if (curIndex >= 0)
    {
        //saving old data before switching to new person
        saveDataToList();
    }

    curIndex = row;
    curInfo = data[row];
    ui.lineEdit->setText(curInfo.name);
    ui.lineEdit_2->setText(curInfo.surname);
    ui.lineEdit_3->setText(curInfo.email);
    ui.lineEdit_4->setText(curInfo.phone);
    ui.textEdit->setPlainText(curInfo.notes);
}

void MainWindow::saveDataToList()
{
    curInfo.name = ui.lineEdit->text();
    curInfo.surname = ui.lineEdit_2->text();
    curInfo.email = ui.lineEdit_3->text();
    curInfo.phone = ui.lineEdit_4->text();
    curInfo.notes = ui.textEdit->toPlainText();
    data[curIndex] = curInfo;
}

void MainWindow::saveData()
{
    saveDataToList();
    Storage::save("data.db", data);
}

void MainWindow::newRow()
{
    Info newInfo;
    data.push_back(newInfo);
    curIndex = data.length() - 1;
    saveDataToList();
    ui.listWidget->addItem(data[curIndex].name + " " + data[curIndex].surname);
    ui.listWidget->setCurrentRow(curIndex);
}
